package com.example.canvasdemo.ui

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.canvasdemo.LoginActivity
import com.example.canvasdemo.R
import com.example.canvasdemo.model.CreateRoomResponse
import com.example.canvasdemo.model.Room
import com.example.canvasdemo.network.ApiService
import com.example.canvasdemo.network.RetrofitClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class RoomListActivity : AppCompatActivity() {

    private lateinit var etRoomName: EditText
    private lateinit var etRoomCapacity: EditText
    private lateinit var btnCreateRoom: Button
    private lateinit var rvRoomList: RecyclerView
    private lateinit var roomAdapter: RoomAdapter
    private lateinit var btnSearchRoom: Button // 新增搜索按钮
    private val roomList = mutableListOf<Room>()
    private val apiService = RetrofitClient.instance.create(ApiService::class.java)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_room_list)

        // 初始化视图
        etRoomName = findViewById(R.id.etRoomName)
        etRoomCapacity = findViewById(R.id.etRoomCapacity)
        btnCreateRoom = findViewById(R.id.btnCreateRoom)
        rvRoomList = findViewById(R.id.rvRoomList)
        btnSearchRoom = findViewById(R.id.btnSearchRoom)

        // 设置 RecyclerView
        rvRoomList.layoutManager = LinearLayoutManager(this)
        roomAdapter = RoomAdapter(roomList) { room -> onRoomClick(room) }
        rvRoomList.adapter = roomAdapter

        // 创建房间按钮点击事件
        btnCreateRoom.setOnClickListener {
            val name = etRoomName.text.toString()
            val capacity = etRoomCapacity.text.toString().toIntOrNull()

            if (name.isEmpty() || capacity == null) {
                Toast.makeText(this, "请输入有效的房间名称和容量", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            createRoom(name, capacity)
        }


        // 搜索房间按钮点击事件
        btnSearchRoom.setOnClickListener {
            val name = etRoomName.text.toString()
            if (name.isEmpty()) {
                Toast.makeText(this, "请输入房间名称", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            searchRoomByName(name)
        }

        // 获取房间列表
        getRoomList()
    }

    private fun createRoom(name: String, capacity: Int) {
        apiService.createRoom(name, capacity)
            .enqueue(object : Callback<CreateRoomResponse> {
                override fun onResponse(call: Call<CreateRoomResponse>, response: Response<CreateRoomResponse>) {
                    if (response.isSuccessful && response.body()?.success == true) {
                        Toast.makeText(this@RoomListActivity, "房间创建成功", Toast.LENGTH_SHORT).show()
                        getRoomList() // 刷新房间列表
                    } else {
                        Toast.makeText(this@RoomListActivity, "房间创建失败", Toast.LENGTH_SHORT).show()
                    }
                }

                override fun onFailure(call: Call<CreateRoomResponse>, t: Throwable) {
                    Toast.makeText(this@RoomListActivity, "网络错误: ${t.message}", Toast.LENGTH_SHORT).show()
                }
            })
    }

    private fun getRoomList() {
        apiService.getRoomList()
            .enqueue(object : Callback<List<Room>> {
                override fun onResponse(call: Call<List<Room>>, response: Response<List<Room>>) {
                    if (response.isSuccessful) {
                        roomList.clear()
                        response.body()?.let { roomList.addAll(it) }
                        roomAdapter.notifyDataSetChanged()
                    } else {
                        Toast.makeText(this@RoomListActivity, "获取房间列表失败", Toast.LENGTH_SHORT).show()
                    }
                }

                override fun onFailure(call: Call<List<Room>>, t: Throwable) {
                    Toast.makeText(this@RoomListActivity, "网络错误: ${t.message}", Toast.LENGTH_SHORT).show()
                }
            })
    }

    private fun searchRoomByName(name: String) {
        apiService.searchRoomByName(name)
            .enqueue(object : Callback<List<Room>> {
                override fun onResponse(call: Call<List<Room>>, response: Response<List<Room>>) {
                    if (response.isSuccessful) {
                        val rooms = response.body()
                        if (rooms != null && rooms.isNotEmpty()) {
                            roomList.clear()
                            roomList.addAll(rooms)
                            roomAdapter.notifyDataSetChanged()
                        } else {
                            Toast.makeText(this@RoomListActivity, "没有找到符合条件的房间", Toast.LENGTH_SHORT).show()
                        }
                    } else {
                        Toast.makeText(this@RoomListActivity, "搜索失败", Toast.LENGTH_SHORT).show()
                    }
                }

                override fun onFailure(call: Call<List<Room>>, t: Throwable) {
                    Toast.makeText(this@RoomListActivity, "网络错误: ${t.message}", Toast.LENGTH_SHORT).show()
                }
            })
    }


    private fun onRoomClick(room: Room) {
        val sharedPrefs = getSharedPreferences("user_prefs", Context.MODE_PRIVATE)
        val userId = sharedPrefs.getLong("userId", 0)

        if (userId <= 0) {
            Toast.makeText(this, "无效的用户ID，请重新登录", Toast.LENGTH_SHORT).show()
            startActivity(Intent(this, LoginActivity::class.java))
            return
        }
        joinRoom(room.id, userId)
    }

    private fun joinRoom(roomId: Long, userId: Long) {
        val requestData = mapOf("userId" to userId)
        apiService.joinRoom(roomId, requestData).enqueue(object : Callback<Map<String, Any>> {
            override fun onResponse(call: Call<Map<String, Any>>, response: Response<Map<String, Any>>) {
                if (response.isSuccessful) {
                    val responseBody = response.body()
                    if (responseBody != null && responseBody["success"] == true) {
                        Toast.makeText(
                            this@RoomListActivity,
                            "成功加入房间: ${responseBody["message"]}",
                            Toast.LENGTH_SHORT
                        ).show()
                        val intent = Intent(this@RoomListActivity, RoomDetailActivity::class.java)
                        intent.putExtra("room_id", roomId)
                        intent.putExtra("user_id", userId)
                        startActivity(intent)
                    } else {
                        Toast.makeText(this@RoomListActivity, "加入房间失败: ${responseBody?.get("message")}", Toast.LENGTH_SHORT).show()
                    }
                } else {
                    Toast.makeText(this@RoomListActivity, "加入房间失败", Toast.LENGTH_SHORT).show()
                }
            }

            override fun onFailure(call: Call<Map<String, Any>>, t: Throwable) {
                Toast.makeText(this@RoomListActivity, "网络错误: ${t.message}", Toast.LENGTH_SHORT).show()
            }
        })
    }
}



